package com.yu.transport.handler;

import com.yu.factory.SingletonFactory;
import com.yu.provider.ServiceProvider;
import com.yu.provider.ServiceProviderImpl;
import com.yu.transfer.RpcRequest;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @PackageName: com.yu.transport.handler
 * @Description: rpc请求处理器,在这里进行目标方法的调用
 * @Version: v1.0.0
 * @Author: yuweilin
 * @Date: 10:09
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ------------------------------------------------------------
 * 2021/2/5      yuweilin         v1.0.0               新建
 */
@Slf4j
public class NettyRequestHandler {
    private final ServiceProvider serviceProvider;

    public NettyRequestHandler() {
        this.serviceProvider = SingletonFactory.getInstance(ServiceProviderImpl.class);
    }

    public Object handle(RpcRequest request){
        Object service = serviceProvider.getService(request.toRpcProperties());
        return invokeTargetMethod(request,service);
    }

    private Object invokeTargetMethod(RpcRequest request,Object service){
        Object result = null;
        try {
            Method method = service.getClass().getMethod(request.getMethodName(), request.getParamTypes());
            result = method.invoke(service,request.getParameters());
            log.info("服务{}成功调用方法{}",request.getInterfaceName(),request.getMethodName());
        }catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e){
            log.error("调用方法错误{}",e.getMessage());
        }
        return result;
    }
}
